package page418;

public class Ticket implements Runnable {
    int fiveAmount = 3, tenAmount = 0;

    public synchronized void saleTicket(int money) {
        if (money == 5) {
            fiveAmount += 1;
            System.out.println("给" + Thread.currentThread().getName() + "票," + Thread.currentThread().getName() + "钱正好");
        } else if (money == 10) {
            while (fiveAmount < 1) {
                try {
                    System.out.println(Thread.currentThread().getName() + "靠边等");
                    wait();
                    System.out.println(Thread.currentThread().getName() + "继续买票");
                } catch (InterruptedException e) {
                }
            }
            tenAmount += 1;
            fiveAmount -= 1;
            System.out.println("给" + Thread.currentThread().getName() + "一张票" + ",找零5块");
        } else if (money == 20) {
            while (fiveAmount < 3 || fiveAmount < 2 && tenAmount < 1) {
                try {
                    System.out.println(Thread.currentThread().getName() + "靠边等");
                    wait();
                    System.out.println(Thread.currentThread().getName() + "继续买票");
                } catch (InterruptedException e) {
                }
            }
            fiveAmount -= 3;
            System.out.println("给" + Thread.currentThread().getName() + "票" + ",找零15块");
        }
        notifyAll();
    }

    public void run() {
        if (Thread.currentThread().getName().equals("张某")) {
            saleTicket(20);
        } else if (Thread.currentThread().getName().equals("李某")) {
            saleTicket(10);
        } else if (Thread.currentThread().getName().equals("赵某")) {
            saleTicket(5);
        }
    }
}
